package com.zhiche.lisa.oms.controller;

import com.alibaba.fastjson.JSON;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.oms.dao.model.Order;
import com.zhiche.lisa.oms.dto.LisaFeeReceivable;
import com.zhiche.lisa.oms.service.IOrderService;
import com.zhiche.lisa.oms.vo.ShipmentInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 订单 接口
 *
 * @author lbl
 * @since 2018-06-20
 */
@RestController
@RequestMapping(value = "/order")
@Api(value = "/order", description = "运单接口", tags = {"牵引车接口"})
public class OrderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IOrderService orderService;

    @Value("${security.jwt.header}")
    private String header;

    @PostMapping(value = "/generateOrder")
    @ApiOperation(value = "获取最新发运指令生成订单", notes = "获取最新发运指令生成订单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> generateShipOrder(List<String> licenses, HttpServletRequest request) {
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            String authHeader = request.getHeader(header);
//            orderService.createOrderByErpShipment(authHeader,licenses);
            result.setData(true);
        } catch (BaseException be) {
            LOGGER.error("OrderController.generateOrder BaseException... ", be);
            result = new RestfulResponse<>(-1, be.getMessage(), false);
        } catch (Exception ex) {
            LOGGER.error("OrderController.generateOrder ERROR... ", ex);
            result = new RestfulResponse<>(-1, "系统异常", false);
        }

        return result;
    }

    @PostMapping(value = "/execute")
    public RestfulResponse<Boolean> executeImp() {
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", true);
        try {
//            String authHeader = request.getHeader(header);
            orderService.getAuthedCarrierPlate();
            result.setData(true);
        } catch (BaseException e) {
            LOGGER.error("OrderController.generateOrder BaseException... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), false);
        } catch (Exception e) {
            LOGGER.error("OrderController.generateOrder ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), false);
        }
        return result;
    }

    @PostMapping(value = "/createOrder")
    @ApiOperation(value = "添加订单", notes = "添加订单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> createOrder(@RequestBody ShipmentInfoVO shipmentInfoVO, HttpServletRequest request) {
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            LOGGER.info("OrderController.createOrder param...{} ", JSON.toJSONString(shipmentInfoVO));
            String authHeader = request.getHeader(header);
            orderService.addOrder(shipmentInfoVO, authHeader);
        } catch (BaseException e) {
            LOGGER.error("OrderController.createOrder BaseException... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), false);
        } catch (Exception e) {
            LOGGER.error("OrderController.createOrder ERROR... ", e);
            result = new RestfulResponse<>(-1, "系统异常", false);
        }
        return result;
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "模拟登陆", notes = "模拟登陆", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> login(@RequestBody ShipmentInfoVO shipmentInfoVO) {
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(orderService.loginWithOutToken(shipmentInfoVO));
        } catch (BaseException e) {
            LOGGER.error("OrderController.createOrder BaseException... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), false);
        } catch (Exception e) {
            LOGGER.error("OrderController.createOrder ERROR... ", e);
            result = new RestfulResponse<>(-1, "系统异常", false);
        }

        return result;
    }

    /**
     * OMS获取应收账款信息
     */
    @PostMapping("/queryFeeReceivableOms")
    @ApiOperation(value = "OMS获取应收账单", notes = "OMS获取应收账单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Map<String, LisaFeeReceivable>> queryFeeReceivableOms(@RequestBody List<String> wayBillDtlIds) {
        LOGGER.info("OrderController.queryFeeReceivableOms（OMS获取应收账单） params : {} ", wayBillDtlIds);
        RestfulResponse<Map<String, LisaFeeReceivable>> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(orderService.queryFeeReceivableOms(wayBillDtlIds));
        } catch (BaseException e) {
            LOGGER.error("OrderController.queryFeeReceivableOms ERROR... ", e);
            result = new RestfulResponse<>(e.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("OrderController.queryFeeReceivableOms ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }

    @GetMapping(value = "/queryOrderById")
    @ApiOperation(value = "/queryOrderById", notes = "根据id查询订单信息", response = RestfulResponse.class)
    public RestfulResponse<Order> queryOrderItem(Long id) {
        LOGGER.info("controller:/Order/queryOrderById data: {}", id);
        RestfulResponse result = new RestfulResponse(0, "成功", null);
        try {
            Order order = orderService.queryOrderById(id);
            result.setData(order);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 查询指令号forTms
     */
    @PostMapping("/queryOrderFromTms")
    @ApiOperation(value = "/queryOrderFromTms", notes = "查询指令号forTms", response = RestfulResponse.class)
    public RestfulResponse<Order> queryOrderFromTms(@RequestBody Map<String, String> params) {
        LOGGER.info("controller:/Order/queryOrderFromTms data: {}", params);
        RestfulResponse<Order> result = new RestfulResponse<>(0, "成功", null);
        try {
            Order order = orderService.queryOrderFromTms(params);
            result.setData(order);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 补偿erp丢失指令-参数车牌号
     */
    @GetMapping("/getErpDisptch")
    @ApiOperation(value = "根据车牌号抓取ERP指令", notes = "根据车牌号抓取ERP指令",
            produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Object> getErpDispatch(@RequestParam String plateNo,
                                                  @RequestParam String tenantId,
                                                  @RequestHeader("Authorization") String authorization) {
        // 则调用接口，抓取调度指令
        LOGGER.info("createOrderByErpShipment  抓取指令 plateno:{},tenant:{}", plateNo, tenantId);
        RestfulResponse<Object> response = new RestfulResponse<>(0, "抓取成功", null);
        try {
            orderService.getErpDispatch(plateNo, authorization, tenantId);
        } catch (BaseException e) {
            LOGGER.error("createOrderByErpShipment  抓取指令失败 BaseException:{}",e.getMessage());
            response.setMessage(e.getMessage());
            response.setCode(-1);
        } catch (Exception e) {
            LOGGER.error("createOrderByErpShipment  抓取指令失败 error:{}",e.getMessage());
            response.setMessage("系统异常");
            response.setCode(-1);
        }
        return response;
    }
}
